#!/bin/sh
#
# Copyright (C) 2000-2023 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Shell script to update MySQL tables to Bacula version 15.0.x
#

OLDVERSION=1025
NEWVERSION=1026

echo " "
echo "This script will update a Bacula MySQL database"
echo " from any from version 12-15 or 1014-$OLDVERSION to version $NEWVERSION"
echo " which is needed to convert from any Bacula Community "
echo " versions 5.0.x, 5.2.x, 7.4.x, 9.x.x to Community version 15.0"
echo " "
echo "Depending on the current version of your catalog, you may"
echo " have to run this script multiple times"
echo " "
bindir=@MYSQL_BINDIR@
PATH="$bindir:$PATH"
db_name=@db_name@

# Special trick to not do the upgrade from 1015 to 1016 with this script
if [ "$1" = "--stop1015" ]; then
    STOP1015=yes
    shift			# remove this option from $*
fi

ARGS=$*

getVersion()
{
    mysql $ARGS -D ${db_name} -e "select VersionId from Version LIMIT 1\G" >/tmp/$$
    DBVERSION=`sed -n -e 's/^VersionId: \(.*\)$/\1/p' /tmp/$$`
}

getVersion

if [ "x$DBVERSION" = x ]; then
    echo " "
    echo "Unable to detect database version, you can specify connection information"
    echo "on the command line."
    echo "Error. Cannot upgrade this database."
    echo " "
    exit 1
fi

if [ "$DBVERSION" -eq "$NEWVERSION" ] ; then
   echo "Current ${db_name} database is up-to-date (version $NEWVERSION)."
   exit 0
fi

if [ "$DBVERSION" -lt 1014 -o "$DBVERSION" -gt $OLDVERSION ] ; then
  if [ "$DBVERSION" -lt 12 -o "$DBVERSION" -gt 16 ] ; then
    echo " "
    echo "The existing database is version $DBVERSION !!"
    echo "This script can only update an existing version 12-16 or 1014-$OLDVERSION database to version $NEWVERSION."
    echo "Error. Cannot upgrade this database."
    echo " "
    exit 1
  fi
fi

# For all versions, we need to create the Index on Media(StorageId)
# It may fail, but it's not a big problem
# mysql $*  <<END-OF-DATA >/dev/null 2> /dev/null
# CREATE INDEX media_storageid_idx ON Media (StorageId);
# END-OF-DATA

if [ "$DBVERSION" -eq 12 ] ; then
    if mysql $*  <<END-OF-DATA
USE ${db_name};

CREATE TABLE RestoreObject (
   RestoreObjectId INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
   ObjectName BLOB NOT NULL,
   RestoreObject LONGBLOB NOT NULL,
   PluginName TINYBLOB NOT NULL,
   ObjectLength INTEGER DEFAULT 0,
   ObjectFullLength INTEGER DEFAULT 0,
   ObjectIndex INTEGER DEFAULT 0,
   ObjectType INTEGER DEFAULT 0,
   FileIndex INTEGER UNSIGNED DEFAULT 0,
   JobId INTEGER UNSIGNED NOT NULL,
   ObjectCompression INTEGER DEFAULT 0,
   PRIMARY KEY(RestoreObjectId),
   INDEX (JobId)
);

CREATE INDEX jobhisto_jobid_idx ON JobHisto (JobId);
UPDATE Version SET VersionId=13;

END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from 12 to 13 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from 12 to 13 failed."
	exit 1
    fi
fi

if [ "$DBVERSION" -eq 13 ] ; then
    if mysql $*  <<END-OF-DATA
USE ${db_name};

ALTER TABLE File ADD COLUMN DeltaSeq smallint default 0;
UPDATE Version SET VersionId=14;

END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from 13 to 14 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from 13 to 14 failed."
	exit 1
    fi
fi

if [ "$DBVERSION" -eq 14 ] ; then
    if mysql $*  <<END-OF-DATA
USE ${db_name};

INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('I', 'Incomplete Job',25);
UPDATE Version SET VersionId=1014;
END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from 14 to 1014 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from 14 to 1014 failed."
	exit 1
    fi
fi

if [ "$DBVERSION" -eq 1014 ] ; then
    if mysql $*  <<END-OF-DATA
USE ${db_name};

ALTER TABLE Media
    ADD COLUMN VolABytes BIGINT UNSIGNED DEFAULT 0,
    ADD COLUMN VolAPadding BIGINT UNSIGNED DEFAULT 0,
    ADD COLUMN VolHoleBytes BIGINT UNSIGNED DEFAULT 0,
    ADD COLUMN VolHoles INTEGER UNSIGNED DEFAULT 0;
UPDATE Version SET VersionId=1015;
END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from 1014 to 1015 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from 1014 to 1015 failed."
	exit 1
    fi
fi

if [ "$DBVERSION" -eq 15 -o "$DBVERSION" -eq 16 ]; then
    # In version 16, the upgrade 1017-1018 is already done
    if [ "$DBVERSION" -eq 16 ]; then
        SKIP1018=1
    fi

    if mysql --skip-reconnect $* <<END-OF-DATA
USE ${db_name};

-- Revert the FileIndex if needed
ALTER TABLE RestoreObject
   MODIFY FileIndex INTEGER UNSIGNED DEFAULT 0;
ALTER TABLE BaseFiles
   MODIFY FileIndex INTEGER UNSIGNED DEFAULT 0;

-- If you re-execute the procedure, you can comment out
-- these two lines

DROP INDEX JobId on File;
DROP INDEX JobId_2 on File;

DROP TABLE IF EXISTS file_temp;

CREATE TABLE file_temp (
   FileId BIGINT UNSIGNED NOT NULL,
   FileIndex INTEGER DEFAULT 0,
   JobId INTEGER UNSIGNED NOT NULL,
   PathId INTEGER UNSIGNED NOT NULL,
   Filename BLOB NOT NULL,
   DeltaSeq SMALLINT UNSIGNED DEFAULT 0,
   MarkId INTEGER UNSIGNED DEFAULT 0,
   LStat TINYBLOB NOT NULL,
   MD5 TINYBLOB
   );

INSERT INTO file_temp (FileId, FileIndex, JobId, PathId, Filename, DeltaSeq,
		       MarkId, LStat, Md5)
   SELECT FileId, FileIndex, JobId, PathId, Filename.Name, DeltaSeq, 
	  MarkId, LStat, Md5
    FROM File JOIN Filename USING (FilenameId);

DROP TABLE Filename;
DROP TABLE File;

ALTER TABLE file_temp RENAME TO File;
ALTER TABLE File
    ADD PRIMARY KEY (FileId),
    MODIFY COLUMN FileId BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    ADD INDEX JobId (JobId),
    ADD INDEX JobId_2 (JobId, PathId, Filename(255));

ALTER TABLE Media CHANGE VolWrites VolWrites BIGINT UNSIGNED DEFAULT 0;
ALTER TABLE UnsavedFiles
    DROP COLUMN FilenameId,
    ADD COLUMN Filename BLOB NOT NULL;

UPDATE Version SET VersionId = 1017;

END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from $DBVERSION to 1017 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from $DBVERSION to 1017 failed."
	exit 1
    fi
fi

if [ "$STOP1015" = "" -a "$DBVERSION" -eq 1015 ]; then
    if mysql --skip-reconnect $* <<END-OF-DATA
USE ${db_name};

DROP INDEX JobId on File;
DROP INDEX JobId_2 on File;

CREATE TABLE file_temp (
   FileId BIGINT UNSIGNED NOT NULL,
   FileIndex INTEGER DEFAULT 0,
   JobId INTEGER UNSIGNED NOT NULL,
   PathId INTEGER UNSIGNED NOT NULL,
   Filename BLOB NOT NULL,
   DeltaSeq SMALLINT UNSIGNED DEFAULT 0,
   MarkId INTEGER UNSIGNED DEFAULT 0,
   LStat TINYBLOB NOT NULL,
   MD5 TINYBLOB
   );

INSERT INTO file_temp (FileId, FileIndex, JobId, PathId, Filename, DeltaSeq,
		       MarkId, LStat, Md5)
   SELECT FileId, FileIndex, JobId, PathId, Filename.Name, DeltaSeq, 
	  MarkId, LStat, Md5
    FROM File JOIN Filename USING (FilenameId);

DROP TABLE Filename;
DROP TABLE File;

ALTER TABLE file_temp RENAME TO File;
ALTER TABLE File
    ADD PRIMARY KEY (FileId),
    MODIFY COLUMN FileId BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    ADD INDEX JobId (JobId),
    ADD INDEX JobId_2 (JobId, PathId, Filename(255));

ALTER TABLE Media CHANGE VolWrites VolWrites BIGINT UNSIGNED DEFAULT 0;
ALTER TABLE Job ADD COLUMN FileTable CHAR(20) default 'File';
ALTER TABLE JobHisto ADD COLUMN FileTable CHAR(20) default 'File';


CREATE TABLE Snapshot (
  SnapshotId	  INTEGER UNSIGNED AUTO_INCREMENT,
  Name		  TINYBLOB NOT NULL,
  CreateTDate	  BIGINT   NOT NULL,
  CreateDate	  DATETIME NOT NULL,
  ClientId	  INTEGER UNSIGNED DEFAULT 0,
  Volume	  TINYBLOB NOT NULL,
  Device	  TINYBLOB NOT NULL,
  Type		  TINYBLOB NOT NULL,
  Retention	  INTEGER DEFAULT 0,
  Comment	  BLOB,
  primary key (SnapshotId)
);

CREATE UNIQUE INDEX snapshot_idx ON Snapshot (Device(255), Volume(255), Name(255));

UPDATE Version SET VersionId = 1016;

END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from 1015 to 1016 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from 1015 to 1016 failed."
	exit 1
    fi
fi

if [ "$DBVERSION" -eq 1016 ] ; then
    if mysql $*  <<END-OF-DATA
USE ${db_name};
CREATE INDEX jobtdate_idx on JobHisto (JobTDate);
ALTER TABLE Snapshot ADD COLUMN JobId INTEGER UNSIGNED DEFAULT 0;
ALTER TABLE Snapshot ADD COLUMN FileSetId INTEGER UNSIGNED DEFAULT 0;
UPDATE Version SET VersionId=1017;
END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from 1016 to 1017 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from 1016 to 1017 failed."
	exit 1
    fi
fi

if [ "$DBVERSION" -eq 1017 ] ; then
    if mysql $*  <<END-OF-DATA
USE ${db_name};
CREATE TABLE FileMedia
(
    JobId	      integer	UNSIGNED  not null,
    FileIndex	      integer	UNSIGNED  not null,
    MediaId	      integer	UNSIGNED  not null,
    BlockAddress      bigint	UNSIGNED  default 0,
    RecordNo	      integer	UNSIGNED  default 0,
    FileOffset	      bigint	UNSIGNED  default 0,
    INDEX (JobId, FileIndex)
);
UPDATE Version SET VersionId=1018;
END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from 1017 to 1018 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from 1017 to 1018 failed."
	exit 1
    fi
fi

# We are coming from version 16, so it's already done
if [ "$SKIP1018" = 1 -a "$DBVERSION" -eq 1018 ]; then
    if mysql $*   <<END-OF-DATA
USE ${db_name};
ALTER TABLE File MODIFY FileIndex INTEGER DEFAULT 0;
ALTER TABLE RestoreObject MODIFY FileIndex INTEGER DEFAULT 0;
ALTER TABLE BaseFiles MODIFY FileIndex INTEGER DEFAULT 0;
UPDATE Version SET VersionId=1019;
END-OF-DATA
    then
	echo "Update of Bacula MySQL tables 1018 to 1019 succeeded. (From 16)"
	getVersion
    else
	echo "Update of Bacula MySQL tables 1018 to 1019 failed. (From 16)"
	exit 1
    fi
fi

if [ "$DBVERSION" -eq 1018 ] ; then
    if mysql $*   <<END-OF-DATA
USE ${db_name};
ALTER TABLE BaseFiles MODIFY COLUMN BaseId BIGINT UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE Media 
   CHANGE COLUMN VolParts VolType INTEGER UNSIGNED DEFAULT 0,
   ADD COLUMN VolParts INTEGER DEFAULT 0,
   ADD COLUMN VolCloudParts INTEGER DEFAULT 0,
   ADD COLUMN LastPartBytes BIGINT DEFAULT 0,
   ADD COLUMN CacheRetention BIGINT DEFAULT 0;

-- If you switch to MySQL 5.7
ALTER TABLE Device ALTER COLUMN CleaningDate DROP DEFAULT;
ALTER TABLE Job
    ALTER COLUMN SchedTime    DROP DEFAULT,
    ALTER COLUMN StartTime    DROP DEFAULT,
    ALTER COLUMN EndTime      DROP DEFAULT,
    ALTER COLUMN RealEndTime  DROP DEFAULT;
ALTER TABLE JobHisto
    ALTER COLUMN SchedTime  DROP DEFAULT,
    ALTER COLUMN StartTime  DROP DEFAULT,
    ALTER COLUMN EndTime    DROP DEFAULT,
    ALTER COLUMN RealEndTime DROP DEFAULT;
ALTER TABLE LocationLog ALTER COLUMN Date DROP DEFAULT;
ALTER TABLE FileSet	ALTER COLUMN CreateTime DROP DEFAULT;
ALTER TABLE Media
    ALTER COLUMN FirstWritten DROP DEFAULT,
    ALTER COLUMN LastWritten DROP DEFAULT,
    ALTER COLUMN LabelDate DROP DEFAULT,
    ALTER COLUMN InitialWrite DROP DEFAULT;
ALTER TABLE Log 	ALTER COLUMN Time DROP DEFAULT;

UPDATE Version SET VersionId=1019;
END-OF-DATA
    then
	echo "Update of Bacula MySQL tables 1018 to 1019 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables 1018 to 1019 failed."
	exit 1
    fi
fi


if [ "$DBVERSION" -eq 1019 ] ; then
    if mysql $*   <<END-OF-DATA
USE ${db_name};
ALTER TABLE Pool ADD COLUMN MaxPoolBytes BIGINT UNSIGNED DEFAULT 0;
ALTER TABLE Job ADD COLUMN PriorJob TINYBLOB;
ALTER TABLE JobHisto ADD COLUMN PriorJob TINYBLOB;
UPDATE Version SET VersionId=1020;
END-OF-DATA
    then
	echo "Update of Bacula MySQL tables 1019 to 1020 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables 1019 to 1020 failed."
	exit 1
    fi
fi

if [ "$DBVERSION" -eq 1020 ] ; then
    if mysql $*   <<END-OF-DATA
USE ${db_name};
ALTER TABLE File
   MODIFY FileIndex INTEGER DEFAULT 0;
ALTER TABLE RestoreObject
   MODIFY FileIndex INTEGER DEFAULT 0;
ALTER TABLE BaseFiles
   MODIFY FileIndex INTEGER DEFAULT 0;
UPDATE Version SET VersionId=1021;
END-OF-DATA
    then
        echo "Update of Bacula MySQL tables 1020 to 1021 succeeded."
        getVersion
    else
        echo "Update of Bacula MySQL tables 1020 to 1021 failed."
        exit 1
    fi
fi

if [ "$DBVERSION" -eq 1021 ] ; then
    if mysql $*   <<END-OF-DATA
USE ${db_name};

CREATE TABLE TagJob
(
   JobId INTEGER UNSIGNED not null,
   Tag   TINYBLOB    not null,
   primary key (JobId, Tag(255))
);

CREATE TABLE TagClient
(
   ClientId INTEGER UNSIGNED not null,
   Tag      TINYBLOB    not null,
   primary key (ClientId, Tag(255))
);

CREATE TABLE TagMedia
(
   MediaId INTEGER UNSIGNED not null,
   Tag      TINYBLOB   not null,
   primary key (MediaId, Tag(255))
);

CREATE TABLE TagObject
(
   ObjectId INTEGER UNSIGNED not null,
   Tag      TINYBLOB    not null,
   primary key (ObjectId, Tag(255))
);

CREATE TABLE Object
(
   ObjectId     BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,

   JobId        INTEGER UNSIGNED  not null,
   Path         BLOB NOT NULL,
   Filename     BLOB NOT NULL,
   PluginName   TINYBLOB NOT NULL,

   ObjectType   TINYBLOB     NOT NULL,
   ObjectName   TINYBLOB     NOT NULL,
   ObjectSource TINYBLOB     NOT NULL,
   ObjectUUID   TINYBLOB     NOT NULL,
   ObjectSize   BIGINT       NOT NULL,
   primary key (ObjectId)
);

create index object_jobid_idx on Object (JobId);
create index object_type_idx on Object  (ObjectType(255));
create index object_name_idx on Object  (ObjectName(255));
create index object_source_idx on Object  (ObjectSource(255));

CREATE TABLE Events
(
    EventsId          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    EventsCode        TINYBLOB NOT NULL,
    EventsType        TINYBLOB NOT NULL,
    EventsTime        DATETIME,
    EventsInsertTime  DATETIME,
    EventsDaemon        TINYBLOB NOT NULL,
    EventsSource      TINYBLOB NOT NULL,
    EventsRef         TINYBLOB NOT NULL,
    EventsText        BLOB NOT NULL,
    primary key (EventsId)
);
create index events_time_idx on Events (EventsTime);
UPDATE Version SET VersionId=1022;
END-OF-DATA
    then
        echo "Update of Bacula MySQL tables 1021 to 1022 succeeded."
        getVersion
    else
        echo "Update of Bacula MySQL tables 1021 to 1022 failed."
        exit 1
    fi
fi

if [ "$DBVERSION" -eq 1022 ] ; then
    if mysql $*   <<END-OF-DATA
USE ${db_name};
ALTER TABLE FileMedia ADD FileMediaId integer auto_increment primary key;
ALTER TABLE JobHisto MODIFY COLUMN JobId int PRIMARY KEY AUTO_INCREMENT;
ALTER TABLE Version MODIFY COLUMN VersionId int PRIMARY KEY;
ALTER TABLE Object ADD ObjectCategory TINYBLOB NOT NULL;
create index object_category_idx on Object  (ObjectCategory(255));
INSERT INTO Events (EventsCode, EventsType, EventsTime, EventsDaemon, EventsSource, EventsRef, EventsText) VALUES
  ('DU0001', 'catalog_update', NOW(), '*SHELL*', 'update_bacula_tables', 'pid$$', 'Catalog schema was updated to 1023');

ALTER TABLE TagJob MODIFY JobId INTEGER UNSIGNED;
ALTER TABLE TagClient MODIFY ClientId INTEGER UNSIGNED;
ALTER TABLE TagObject MODIFY ObjectId INTEGER UNSIGNED;
ALTER TABLE Object MODIFY JobId INTEGER UNSIGNED;
ALTER TABLE Snapshot MODIFY ClientId INTEGER UNSIGNED DEFAULT 0;
ALTER TABLE TagMedia MODIFY MediaId INTEGER UNSIGNED;
UPDATE Version SET VersionId=1023;
END-OF-DATA
    then
        echo "Update of Bacula MySQL tables 1022 to 1023 succeeded."
        getVersion
    else
        echo "Update of Bacula MySQL tables 1022 to 1023 failed."
        exit 1
    fi
fi

if [ "$DBVERSION" -eq 1023 ] ; then
    if mysql $*   <<END-OF-DATA
USE ${db_name};
ALTER TABLE Object
    ADD ObjectStatus BINARY(1) DEFAULT 'U',
    ADD ObjectCount  INTEGER UNSIGNED DEFAULT 1,
    ADD INDEX object_status_idx (ObjectStatus);
INSERT INTO Events (EventsCode, EventsType, EventsTime, EventsDaemon, EventsSource, EventsRef, EventsText) VALUES
  ('DU0001', 'catalog_update', NOW(), '*SHELL*', 'update_bacula_tables', 'pid$$', 'Catalog schema was updated to 1024');
UPDATE Version SET VersionId=1024;
END-OF-DATA
    then
        echo "Update of Bacula MySQL tables 1023 to 1024 succeeded."
        getVersion
    else
        echo "Update of Bacula MySQL tables 1023 to 1024 failed."
        exit 1
    fi
fi

if [ "$DBVERSION" -eq 1024 ] ; then
    if mysql $* -f  <<END-OF-DATA
USE ${db_name};
ALTER TABLE Client ADD COLUMN Plugins VARCHAR(255) DEFAULT '';

-- --------------------------------------------------------------
-- MetaData Index

CREATE TABLE MetaEmail
(
    EmailPKId  BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, -- Used for replication
    EmailTenant     		VARCHAR(255),
    EmailOwner       		VARCHAR(255),
    EmailId          		VARCHAR(255),
    EmailTime         		DATETIME,
    EmailTags         		TEXT,
    EmailSubject      		TEXT,
    EmailFolderName   		TEXT,
    EmailFrom         		VARCHAR(255),
    EmailTo           		TEXT,
    EmailCc           		TEXT,
    EmailInternetMessageId 	VARCHAR(255),
    EmailBodyPreview  		TEXT,
    EmailImportance   		VARCHAR(255),
    EmailConversationId    	VARCHAR(255),
    EmailIsRead       		TINYINT,
    EmailIsDraft      		TINYINT,
    EmailHasAttachment 		TINYINT,
    EmailSize	 			INTEGER,
    Plugin       			VARCHAR(255),
    FileIndex   	 		INTEGER,
    JobId        			INTEGER,
    PRIMARY KEY(EmailPKId)
);

-- Requires TEXT instead of BLOB
CREATE FULLTEXT INDEX meta_emailsubjectbody ON MetaEmail 
       (EmailSubject, EmailBodyPreview, EmailTo, EmailCc, EmailFrom);
CREATE INDEX meta_emailowner ON MetaEmail (EmailTenant(255), EmailOwner(255));
CREATE INDEX meta_emailtime on MetaEmail (EmailTime);
CREATE INDEX meta_emailtags on MetaEmail (EmailTags(255));
CREATE INDEX meta_emailfoldername on MetaEmail (EmailFolderName(255));
CREATE INDEX meta_emailconversationid on MetaEmail (EmailConversationId(255));
CREATE INDEX meta_emailisread on MetaEmail (EmailIsRead);
CREATE INDEX meta_emailhasattachment on MetaEmail (EmailHasAttachment);
CREATE INDEX meta_emailjobid on MetaEmail (Jobid);

CREATE TABLE MetaAttachment
(
    AttachmentPKId  BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, -- Used for replication
    AttachmentTenant            VARCHAR(255),
    AttachmentOwner    		VARCHAR(255),
    AttachmentName     		TEXT,
    AttachmentEmailId  		VARCHAR(255),
    AttachmentContentType 	VARCHAR(255),
    AttachmentIsInline 		SMALLINT,
    AttachmentSize	 		INTEGER,
    Plugin      			VARCHAR(255),
    FileIndex    			INTEGER,
    JobId        			INTEGER,
    PRIMARY KEY(AttachmentPKId)
);

CREATE INDEX meta_attachmentowner ON MetaAttachment (AttachmentTenant,AttachmentOwner);
CREATE INDEX meta_attachmentemailid ON MetaAttachment (AttachmentEmailId);
CREATE INDEX meta_attachmentjobid on MetaAttachment (Jobid);

INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('l', 'Doing data despooling',15),
   ('L', 'Committing data (last despool)',15),
   ('u', 'Cloud upload',15),
   ('w', 'Cloud download',15),
   ('q', 'Queued waiting for device',15),
   ('W', 'Terminated normally with warnings',25);

ALTER TABLE RestoreObject MODIFY ObjectName MEDIUMBLOB;
ALTER TABLE RestoreObject MODIFY PluginName BLOB;
ALTER TABLE Object MODIFY PluginName BLOB;
INSERT INTO Events (EventsCode, EventsType, EventsTime, EventsDaemon, EventsSource, EventsRef, EventsText) VALUES
  ('DU0001', 'catalog_update', NOW(), '*SHELL*', 'update_bacula_tables', 'pid$$', 'Catalog schema was updated to 1025');
UPDATE Version SET VersionId=1025;
END-OF-DATA
    then
        echo "Update of Bacula MySQL tables 1024 to 1025 succeeded."
        getVersion
    else
        echo "Update of Bacula MySQL tables 1024 to 1025 failed."
        exit 1
    fi
fi

if [ "$DBVERSION" -eq 1025 ] ; then
    if mysql $* -f <<END-OF-DATA
USE ${db_name};
CREATE TABLE MalwareMD5
(
    MD5     char(22)       -- Same as in File
);
CREATE INDEX malwaremd5_idx on MalwareMD5 (MD5);

CREATE TABLE MalwareSHA256
(
    MD5     char(65)       -- Same as in File
);
CREATE INDEX malwaresha256_idx on MalwareSHA256 (MD5);

CREATE TABLE FileEvents 
(
   Id   BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, -- Used for replication
   Time DATETIME DEFAULT NOW(),
   SourceJobId   int,        -- Can be the Verify job id for example, or the jobid during a restore/backup
   JobId         int,        -- JobId where the file was found. Used for pruning
   FileIndex     int,        -- File reference
   Type          char,       -- Event type (antivirus, malware scanning (M), lost file)
   Description   blob,       -- Description of the event
   Severity      int,        -- level of severity. (0 OK, 100 Important)
   Source        blob,       -- Information about the source of the event
   PRIMARY KEY(Id)
);

CREATE INDEX FileEvents_jobid_idx ON FileEvents (JobId, FileIndex);
CREATE INDEX FileEvents_sourcejobid_idx ON FileEvents (SourceJobId);


DROP INDEX meta_emailsubjectbody ON MetaEmail;
DROP INDEX meta_emailowner ON MetaEmail;
DROP INDEX meta_emailconversationid on MetaEmail;

ALTER TABLE MetaEmail
    MODIFY COLUMN EmailTenant TEXT,
    MODIFY COLUMN EmailOwner TEXT,
    MODIFY COLUMN EmailId TEXT,
    MODIFY COLUMN EmailFrom TEXT,
    MODIFY COLUMN EmailInternetMessageId TEXT,
    MODIFY COLUMN EmailConversationId TEXT,
    MODIFY COLUMN Plugin TEXT;

CREATE FULLTEXT INDEX meta_emailsubjectbody ON MetaEmail 
       (EmailSubject, EmailBodyPreview, EmailTo, EmailCc, EmailFrom);
CREATE INDEX meta_emailowner ON MetaEmail (EmailTenant(255), EmailOwner(255));
CREATE INDEX meta_emailconversationid on MetaEmail (EmailConversationId(255));
CREATE INDEX meta_emailid on MetaEmail (EmailId(255));


DROP INDEX meta_attachmentowner ON MetaAttachment;
DROP INDEX meta_attachmentemailid ON MetaAttachment;

ALTER TABLE MetaAttachment
    MODIFY COLUMN AttachmentTenant TEXT,
    MODIFY COLUMN AttachmentOwner  TEXT,
    MODIFY COLUMN AttachmentEmailId TEXT,
    MODIFY COLUMN Plugin           TEXT;

CREATE INDEX meta_attachmentowner ON MetaAttachment (AttachmentTenant(255),AttachmentOwner(255));
CREATE INDEX meta_attachmentemailid ON MetaAttachment (AttachmentEmailId(255));

ALTER TABLE Media
    ADD COLUMN Protected    tinyint default 0,
    ADD COLUMN UseProtect   tinyint default 0,
    ADD COLUMN VolEncrypted tinyint default 0;

ALTER TABLE Object
    ADD COLUMN FileIndex integer not null default 0,
    MODIFY COLUMN ObjectSource BLOB,
    MODIFY COLUMN ObjectName BLOB,
    MODIFY COLUMN ObjectType BLOB,
    MODIFY COLUMN ObjectCategory BLOB,
    MODIFY COLUMN ObjectUUID BLOB;

ALTER TABLE FileSet
    ADD COLUMN Content BLOB;

ALTER TABLE Job
    ADD COLUMN RealStartTime DATETIME,
    ADD COLUMN isVirtualFull     TINYINT    default 0,
    ADD COLUMN CompressRatio     float      default 0,
    ADD COLUMN Rate              float      default 0,
    ADD COLUMN LastReadStorageId Integer    default 0,
    ADD COLUMN LastReadDevice    blob,
    ADD COLUMN WriteStorageId    integer    default 0,
    ADD COLUMN WriteDevice       blob,
    ADD COLUMN StatusInfo        blob,
    ADD COLUMN Encrypted         int        default 0;

ALTER TABLE JobHisto
    ADD COLUMN RealStartTime DATETIME,
    ADD COLUMN isVirtualFull     TINYINT    default 0,
    ADD COLUMN CompressRatio     float      default 0,
    ADD COLUMN Rate              float      default 0,
    ADD COLUMN LastReadStorageId Integer    default 0,
    ADD COLUMN LastReadDevice    blob,
    ADD COLUMN WriteStorageId    integer    default 0,
    ADD COLUMN WriteDevice       blob,
    ADD COLUMN StatusInfo        blob,
    ADD COLUMN Encrypted         int        default 0;

INSERT INTO Events (EventsCode, EventsType, EventsTime, EventsDaemon, EventsSource, EventsRef, EventsText) VALUES
  ('DU0001', 'catalog_update', NOW(), '*SHELL*', 'update_bacula_tables', 'pid$$', 'Catalog schema was updated to 1026');
UPDATE Version SET VersionId=1026;
END-OF-DATA
    then
	echo "Update of Bacula MySQL tables from 1025 to 1026 succeeded."
	getVersion
    else
	echo "Update of Bacula MySQL tables from 1025 to 1026 failed."
	exit 1
    fi
fi

exit 0
